package com.opendeepsearch.tool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

// Tavily搜索工具

public class TavilySearchTool implements Tool {
    private static final Logger logger = LoggerFactory.getLogger(TavilySearchTool.class);
    private final String apiKey;

    public TavilySearchTool(String apiKey) {
        if (apiKey == null || apiKey.trim().isEmpty()) {
            throw new IllegalArgumentException("Tavily API key cannot be null or empty");
        }
        this.apiKey = apiKey;
    }

    @Override
    public String getName() {
        return "tavily_search";
    }

    @Override
    public String getDescription() {
        return "使用Tavily API进行网络搜索";
    }

    @Override
    public String execute(String input) throws IOException, InterruptedException, URISyntaxException {
        if (input == null || input.trim().isEmpty()) {
            throw new IllegalArgumentException("Search input cannot be null or empty");
        }
        
        logger.debug("搜索输入：{}", input);
        String apiUrl = "https://api.tavily.com/search";
        
        HttpClient client = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(10))
                .build();

        // Create JSON request body
        String escapedInput = input.replace("\"", "\\\"");
        String requestBody = String.format("{\"query\": \"%s\", \"max_results\": 10}", escapedInput);

        HttpRequest request = HttpRequest.newBuilder()
                .uri(new URI(apiUrl))
                .timeout(Duration.ofSeconds(15))
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer " + apiKey)
                .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() == HttpURLConnection.HTTP_OK) {
            logger.debug("搜索成功：{}", response.body());
            return response.body();
        } else {
            String errorMsg = "搜索失败: " + response.statusCode() + " - " + response.body();
            logger.error(errorMsg);
            throw new IOException(errorMsg);
        }
    }
}
